package com.iyao_app.im.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.JsonBean;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.im.factory.ThreadPoolFactory;
import com.iyao_app.im.uitl.GetJsonDataUtil;
import com.iyao_app.mvp.info.VisionImpressionActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.ToastUtil;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonalDataActivity extends BaseActivityWithHead {


    @BindView(R.id.iv_head_picture)
    SimpleDraweeView mIvHeadPicture;
    @BindView(R.id.rl_head_picture)
    RelativeLayout mRlHeadPicture;
    @BindView(R.id.tv_nick_name)
    EditText mTvNickName;
    @BindView(R.id.rl_nick_name)
    RelativeLayout mRlNickName;
    @BindView(R.id.tv_birthday_)
    TextView mTvBirthday;
    @BindView(R.id.rl_birthday_)
    RelativeLayout mRlBirthday;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.rl_sex)
    RelativeLayout mRlSex;
    @BindView(R.id.tv_city)
    TextView mTvCity;
    @BindView(R.id.rl_city)
    RelativeLayout mRlCity;
    @BindView(R.id.sv_dianji)
    ScrollView mSvDianji;

    private TimePickerView pvTime;
    private long birthDay = 0;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(MessageEvent event) {
        if (event.getState() == MessageEvent.USER_INFO_REFUSH) {
            initView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {

        setTitleTV(ResourcesUtils.getString(R.string.geren));
        user = DbUtil.getUser();
        String avatarUrl = user.avatarUrl;
        String nickname = user.nickname;
        long birthday = user.birthday;
        if (birthday != 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
            Date date = new Date(birthday);
            String format = simpleDateFormat.format(date);
            LogUtil.e("===" + format);
            mTvBirthday.setText(format);
        }

        int sex = user.sex;
        String city = user.city;

        mIvHeadPicture.setImageURI(avatarUrl);
        mTvNickName.setText(nickname);

        if (sex == 1) {
            mTvSex.setText("男");
        } else if (sex == 2) {
            mTvSex.setText("女");
        }
        mTvCity.setText(city);
    }

    @OnClick({R.id.rl_head_picture, R.id.rl_nick_name, R.id.rl_birthday_, R.id.rl_sex, R.id.rl_city, R.id.rl_vision, R.id.sv_dianji})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_head_picture:
                Intent intenthead = new Intent(this, HeadPictureActivity.class);
                intenthead.putExtras(getIntent());
                startActivity(intenthead);
                break;
            case R.id.rl_nick_name:
                unfocused();
                break;
            case R.id.rl_birthday_:
                timePick();
                break;
            case R.id.rl_sex:
                user.sex = 1;
                DbUtil.updateUserInfo(user);
                MessageEvent messageEvent = new MessageEvent(MessageEvent.USER_INFO_REFUSH);
                EventBus.getDefault().post(messageEvent);
                break;
            case R.id.rl_city:
//                myHandler.sendEmptyMessage(MSG_LOAD_DATA);
                break;
            case R.id.rl_vision:
                Intent intent = new Intent(this, VisionImpressionActivity.class);
                intent.putExtras(getIntent());
                startActivity(intent);
                break;
            case R.id.sv_dianji:
                KeyboardUtils.hideSoftInput(this);
                unfocused();
                break;
        }
    }


    private void unfocused() {
        if (mTvNickName.getText().toString().trim() == null) {
            ToastUtil.showToast(this, "不能为空");
            if (mTvNickName.getText().toString().trim() != user.nickname) {
                String trim = mTvNickName.getText().toString().trim();
                user.nickname = trim;
                DbUtil.updateUserInfo(user);
                MessageEvent messageEvent = new MessageEvent(MessageEvent.USER_INFO_REFUSH);
                EventBus.getDefault().post(messageEvent);
                modificationNickName(trim);

            }
        }

    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                Toast.makeText(PersonalDataActivity.this, tx, Toast.LENGTH_SHORT).show();


            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    MyHandler myHandler = new MyHandler(this);

    static class MyHandler extends Handler {
        WeakReference<PersonalDataActivity> mActivityReference;

        MyHandler(PersonalDataActivity activity) {
            mActivityReference = new WeakReference<PersonalDataActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final PersonalDataActivity activity = mActivityReference.get();
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    LogUtil.e("Begin Parse Data");
                    ThreadPoolFactory.getNormalPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            // 写子线程中的操作,解析省市区数据
                            activity.initJsonData();
                        }
                    });

                    break;

                case MSG_LOAD_SUCCESS:
                    LogUtil.e("Parse Succeed");
                    activity.ShowPickerView();
                    break;

                case MSG_LOAD_FAILED:
                    LogUtil.e("Parse Failed");
                    break;
            }


        }
    }

    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        myHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = JSON.parseObject(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            myHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void timePick() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        selectedDate.set(1990, 0, 1);
        //正确设置方式 原因：注意事项有说明
        startDate.set(1900, 1, 1);

        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (date != null) {
                    @SuppressLint("SimpleDateFormat") String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy.MM.dd"));
                    mTvBirthday.setText(time);
                    birthDay = date.getTime();
                    user.birthday = birthDay;
                    DbUtil.updateUserInfo(user);
                    MessageEvent messageEvent = new MessageEvent(MessageEvent.USER_INFO_REFUSH);
                    EventBus.getDefault().post(messageEvent);
                    modificationBirthDay(birthDay);
                }
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setTextColorCenter(Color.WHITE)
                .setTextColorOut(Color.GRAY)
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(ResourcesUtils.getColor(R.color.app_black_bg))//标题背景颜色 Night mode
                .setBgColor(ResourcesUtils.getColor(R.color.app_black_bg))
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unfocused();
    }

    /**
     * 修改生日
     *
     * @param birthDay
     */
    private void modificationBirthDay(long birthDay) {
        NetUtils.getInstance().userUpdateBirthDay(user.id, birthDay, new NetCallBack() {
            @Override
            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {

                } else {

                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }

    /**
     * 修改名字
     *
     * @param nickname
     */
    private void modificationNickName(String nickname) {
        NetUtils.getInstance().userUpdate(user.id, null, null, nickname, new NetCallBack() {
            @Override
            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {

                } else {

                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }
}
